#!/bin/bash
# load_testmod
#***************************************************************
# This program is part of the source code released for the book
#  "Linux Kernel Debugging"
# (c) Author: Kaiwan N Billimoria
# Publisher:  Packt
# GitHub repository:
# https://github.com/PacktPublishing/Linux-Kernel-Debugging
#
# From: Ch 5: Debugging kernel memory issues
#***************************************************************
# Simple bash wrapper to setup our custom testcases for KASAN & UBSAN.
name=$(basename $0)
# TODO
# locate_kernel_config()
KCONF=/boot/config-$(uname -r)

setup_testmod()
{
KMOD=test_kmembugs
if grep -q "CONFIG_CC_IS_GCC=y" ${KCONF}; then
   CCVAR=gcc
   echo "This kernel has been built with gcc"
elif grep -q "CONFIG_CC_IS_CLANG=y" ${KCONF}; then
   CCVAR=clang
   echo "This kernel has been built with clang"
fi
make CC=${CCVAR} || return
[ ! -f ${KMOD}.ko ] && {
   echo "Module ${KMOD}.ko not built? aborting..."
   exit 1
}
sudo rmmod ${KMOD} 2>/dev/null
sudo dmesg -C
sudo insmod ./${KMOD}.ko
sudo dmesg
}

#--- 'main' here

echo "Kernel ver: $(uname -r)"
ubsan=1
kasan=1
if ! grep -q "CONFIG_UBSAN=y" ${KCONF}; then
   echo "UBSAN disabled for this kernel"
   ubsan=0
else
   echo "UBSAN enabled"
fi
if ! grep -q "CONFIG_KASAN_GENERIC=y" ${KCONF}; then
   echo "Generic KASAN disabled for this kernel"
   kasan=0
else
   echo "Generic KASAN enabled"
fi
[[ ${ubsan} -eq 0 ]] && [[ ${kasan} -eq 0 ]] && {
   echo "=== NOTE! Both KASAN and UBSAN are disabled for this kernel ==="
}
val=0
[ ${kasan} -eq 1 ] && val=1
setup_testmod ${val}
exit 0
